package com.zjf.util;

import org.apache.commons.digester.Digester;
import org.xml.sax.SAXException;

import com.zjf.entity.Article;
import com.zjf.entity.Blog;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class RssParseUtil { 
	public  Blog parseRss(String filename) throws IOException, SAXException{
		Digester digester = new Digester();
		digester.addObjectCreate("rss", Blog.class);
		digester.addObjectCreate("rss/channel/item", Article.class);
		digester.addSetNext("rss/channel/item", "addArticle");
		digester.addBeanPropertySetter("rss/channel/item/title", "title");
		digester.addBeanPropertySetter("rss/channel/item/description", "content");
		digester.addBeanPropertySetter("rss/channel/item/pubDate","pubDate");
		
		InputStream input = new FileInputStream(new File(filename));
		Blog blog = (Blog)digester.parse(input);
		input.close();
		for(Article a:blog.getArticles()){
			System.out.println(a.getTitle());
		}
		return blog;
	}
	public  Blog parseRss(InputStream ips) throws IOException, SAXException{
		Digester digester = new Digester();
		digester.addObjectCreate("rss", Blog.class);
		digester.addObjectCreate("rss/channel/item", Article.class);
		digester.addSetNext("rss/channel/item", "addArticle");
		digester.addBeanPropertySetter("rss/channel/item/title", "title");
		digester.addBeanPropertySetter("rss/channel/item/description", "content");
		digester.addBeanPropertySetter("rss/channel/item/pubDate","pubDate");
		
		Blog blog = (Blog)digester.parse(ips);
		ips.close();
		for(Article a:blog.getArticles()){
			System.out.println(a.getTitle());
		}
		return blog;
	}
	
}
